#!/bin/bash
set -euo pipefail

# --------------------------
# Configuration & Usage
# --------------------------
usage() {
    echo "Usage: $0 [target]"
    echo "Targets:"
    echo "  sdlock   - Build DEB for SDL3-based lock program"
    echo "  xlock    - Build DEB for X11-based lock program"
    echo "  rlock    - Build DEB for raylib-based lock program"
    exit 1
}

# Common base config
PKG_VERSION="0.99"
PKG_ARCH="amd64"
MAINTAINER="etcix<1690544550@qq.com>"
SRC_DIR="$(pwd)"
TMP_BUILD_DIR="${SRC_DIR}/tmp_build"  # Per-target temp dir
BIN_DEST="${TMP_BUILD_DIR}/usr/local/bin"


# --------------------------
# Set Target-Specific Config
# --------------------------
set_target_config() {
    local target="$1"

    case "${target}" in
        sdlock)
            PKG_NAME="sdlock"
            SRC_FILE="${SRC_DIR}/sdlock.c"
            PKG_DESCRIPTION="SDL3-based system screen locker
 Secure PAM-authenticated screen locker using SDL3 for rendering.
 Features password masking, cursor navigation, and failed attempt tracking."
            DEPENDS="libc6 (>= 2.28), libpam0g (>= 1.1.8), libfreetype6"
            COMPILE_FLAGS="-I ${SRC_DIR}/include \
                           -L ${SRC_DIR}/lib \
                           -l:libSDL3.a \
                           -lpam \
                           -lm \
                           $(pkg-config --cflags --libs freetype2) \
                           -Wall \
                           -Wextra \
                           -Wno-bool-compare \
                           -Wno-sign-compare \
                           -Wno-char-subscripts"
            ;;

        xlock)
            PKG_NAME="xlock"
            SRC_FILE="${SRC_DIR}/xlock.c"
            PKG_DESCRIPTION="X11-based lightweight screen locker
 Minimalist screen locker using X11/Xft for rendering.
 Secure PAM authentication with minimal system dependencies."
            DEPENDS="libc6 (>= 2.28), libpam0g (>= 1.1.8), libx11-6, libxft2, libfreetype6"
            COMPILE_FLAGS="-lX11 \
                           -lXft \
                           -lpam \
                           $(pkg-config --cflags --libs freetype2) \
                           -Wall \
                           -Wextra \
                           -Wno-deprecated-declarations \
                           -Wno-sign-compare"
            ;;

        rlock)
            PKG_NAME="rlock"
            SRC_FILE="${SRC_DIR}/rlock.c"
            PKG_DESCRIPTION="Raylib-based hardware-accelerated screen locker
 Screen locker using raylib for GPU-accelerated rendering.
 Secure PAM authentication with modern UI features."
            DEPENDS="libc6 (>= 2.28), libpam0g (>= 1.1.8)"
            COMPILE_FLAGS="-I ${SRC_DIR}/../include \
                           -L ${SRC_DIR}/../lib \
                           -l:libraylib.a \
                           -lm \
                           -lpam \
                           -Wall \
                           -Wextra"
            ;;

        *)
            echo "Error: Invalid target '${target}'"
            usage
            ;;
    esac

    # Derived paths for current target
    DEB_DEST="${SRC_DIR}/${PKG_NAME}_${PKG_VERSION}_${PKG_ARCH}.deb"
}


# --------------------------
# Dependency Checks
# --------------------------
check_core_deps() {
    echo "=== Checking core build dependencies ==="
    local deps=(
        "gcc:gcc"
        "dpkg-deb:dpkg-dev"
        "pkg-config:pkg-config"
    )

    for dep in "${deps[@]}"; do
        local cmd="${dep%:*}"
        local pkg="${dep#*:}"
        if ! command -v "${cmd}" &> /dev/null; then
            echo "ERROR: '${cmd}' not found. Install with: sudo apt install ${pkg}"
            exit 1
        fi
    done
}

check_target_deps() {
    local target="$1"
    echo -e "\n=== Checking ${target}-specific dependencies ==="

    # Check source file exists
    if [ ! -f "${SRC_FILE}" ]; then
        echo "ERROR: Missing source file: ${SRC_FILE}"
        exit 1
    fi

    # Target-specific library checks
    case "${target}" in
        sdlock)
            if [ ! -d "${SRC_DIR}/include" ] || [ ! -f "${SRC_DIR}/lib/libSDL3.a" ]; then
                echo "ERROR: SDL3 files missing!"
                echo "Ensure: ${SRC_DIR}/include (headers) and ${SRC_DIR}/lib/libSDL3.a (static lib)"
                exit 1
            fi
            ;;

        xlock)
            if ! pkg-config --exists x11 xft; then
                echo "ERROR: X11 dependencies missing. Install with:"
                echo "  sudo apt install libx11-dev libxft-dev"
                exit 1
            fi
            ;;

        rlock)
            if [ ! -d "${SRC_DIR}/../include" ] || [ ! -f "${SRC_DIR}/../lib/libraylib.a" ]; then
                echo "ERROR: Raylib files missing!"
                echo "Ensure: ${SRC_DIR}/../include (headers) and ${SRC_DIR}/../lib/libraylib.a (static lib)"
                exit 1
            fi
            ;;
    esac

    # Common PAM check (all targets use PAM)
    if [ ! -f "/usr/include/security/pam_appl.h" ]; then
        echo "ERROR: PAM development files missing. Install with:"
        echo "  sudo apt install libpam0g-dev"
        exit 1
    fi
}


# --------------------------
# Build Logic
# --------------------------
build_deb() {
    local target="$1"
    echo -e "\n=== Starting ${PKG_NAME} DEB build ==="

    # Clean previous build artifacts
    echo -e "\n=== Cleaning previous build ==="
    rm -rf "${TMP_BUILD_DIR}" "${DEB_DEST}"
    mkdir -p "${BIN_DEST}" "${TMP_BUILD_DIR}/DEBIAN"

    # Compile binary (no execution)
    echo -e "\n=== Compiling ${PKG_NAME} ==="
    gcc -o "${BIN_DEST}/${PKG_NAME}" \
        "${SRC_FILE}" \
        ${COMPILE_FLAGS}

    # Create DEBIAN control file
    echo -e "\n=== Creating package metadata ==="
    cat > "${TMP_BUILD_DIR}/DEBIAN/control" << EOF
Package: ${PKG_NAME}
Version: ${PKG_VERSION}
Section: utils
Priority: optional
Architecture: ${PKG_ARCH}
Maintainer: ${MAINTAINER}
Depends: ${DEPENDS}
Description: ${PKG_DESCRIPTION}
EOF
    chmod 755 "${TMP_BUILD_DIR}/DEBIAN"

    # Verify binary exists and is executable (no execution)
    echo -e "\n=== Verifying build ==="
    if [ ! -f "${BIN_DEST}/${PKG_NAME}" ] || [ ! -x "${BIN_DEST}/${PKG_NAME}" ]; then
        echo "ERROR: ${PKG_NAME} binary not created or not executable"
        exit 1
    fi
    echo "✓ ${PKG_NAME} binary verified"

    # Build DEB package
    echo -e "\n=== Building DEB package ==="
    dpkg-deb --build --root-owner-group "${TMP_BUILD_DIR}" "${DEB_DEST}"

    # Cleanup temporary files
    echo -e "\n=== Cleaning up ==="
    rm -rf "${TMP_BUILD_DIR}"

    echo -e "\n=== ${PKG_NAME} build complete! ==="
    echo "Package: ${DEB_DEST}"
    echo "Install with: sudo dpkg -i ${DEB_DEST}"
}


# --------------------------
# Main Execution
# --------------------------
if [ $# -ne 1 ]; then
    usage
fi

TARGET="$1"
set_target_config "${TARGET}"
check_core_deps
check_target_deps "${TARGET}"
build_deb "${TARGET}"
